2023/12/233699字符

类型约束

类型 规则
any 任意类型
unknown 类型安全的任意类型
boolean 布尔类型
number 数字
string 字符串
animal 字面量,定义什么就只能赋值什么 let animal: 'dog'
number[] / string[] / any[] 数组,并指定每一项的类型
array 任意 JS 数组
object 任意的 JS 对象
null / undefined 子类型,赋值给其他类型
void 通常约束函数的返回值,不返回
never 没有值,也不能是任何值。通常约束函数的返回值,该函数永远不会结束
tuple 元素,TS新增类型,固定长度数组 let tuple: [string, number]

仅需在 变量、函数的参数、函数的返回值位置上加 : 类型

let num: number;

function sum (a: number, b: number): number {
    return a + b;
}
num = sum(2, 3);  //--> 5

let str: string | undefined;  // 联合类型
if (typeof str === 'string') {
    // 类型保护
    str.toUpperCase();
}

let sex: "男" | "女";        // 字面量约束,不可更改
let arr: [string, number];  // 要求数组只能有两项,第一项为 string,第二项为 number

type User = {           // 对象严格约束
    name: string,
    age: number
}
function fn (): User {  // 类型引用
    return {
        name: 'bozai',
        age: 18
    }
}

枚举

  • 枚举字段值可以是字符串或数字
enum Sex {
    male = "男",
    femle = "女"
}

let sex = Sex.male;
enum Nums {
    num1, num2, num3, num4
}

console.log(Nums.num2);  //--> 1

Nums 中都不进行赋值,会以 0 开始逐次递增

函数类型约束

// 规定类型只有两种情况
function combine (a: number, b: number): number;
function combine (a: string, b: string): string;
function combine (a, b) {
    if (typeof a === 'number' && typeof b === 'number') return a * b;
    if (typeof a === 'string' && typeof b === 'string') return a + b;
}

combine(1, 2);

可选参数 ? 或选用 ES6 默认参数方法

function (a, b, c?) {
    if (c) return a + b + c;
    return a + b;
}

创建一副扑克

type Deck = NormalCard[]  // 一副扑克
enum Color {  // 花色
    heart = "♥",
    spade = "♠",
    club = "♣",
    diamond = "♦"
}
enum Mark {
    One = 'A',
    Two = '2',
    Three = '3',
    Four = '4',
    Five = '5',
    Six = '6',
    Seven = '7',
    Eight = '8',
    Nine = '9',
    Ten = '10',
    Eleven = 'J',
    Twelve = 'Q',
    Thirteen = 'K'
}
type NormalCard = {  // 按数字将扑克分成数组
    color: Color,
    mark: Mark
}

// 创建一副扑克牌
function createDeck(): Deck {
    const deck: Deck = [];
    const mark = Object.values(Mark)
    const colors = Object.values(Color)
    for (const m in mark) {
        for (const c in colors) {
            deck.push({
                color: colors[c],
                mark: mark[m]
            })
        }
    }
    return deck;
}

// 输出扑克牌
function printDeck(deck: Deck) {
    let result = '';
    deck.forEach((val, i) => {
        let str = val.color + val.mark;
        result += str + ' ';
    })
    console.log(result)
}

printDeck(createDeck());  //--> ♥A ♠A ♣A ♦A ♥2 ♠2 ♣2 ♦2 ♥3 ♠3 ♣3 ♦3 ♥4 ♠4 ♣4 ♦4 ♥5 ♠5 ♣5 ♦5 ♥6 ♠6 ♣6 ♦6 ♥7 ♠7 ♣7 ♦7 ♥8 ♠8 ♣8 ♦8 ♥9 ♠9 ♣9 ♦9 ♥10 ♠10 ♣10 ♦10 ♥J ♠J ♣J ♦J ♥Q ♠Q ♣Q ♦Q ♥K ♠K ♣K ♦K